import { Err_revc } from "../package/protocol/ProtoDef";
import { ProtoMod } from "../package/protocol/proto";

/**
 * 所有的路由信息
 */
const routers = {
    3253: "connector.entryHandler.entry",
    3500: "connector.petHandler.doBuyFlute",
};

/**
 * 自定义解密数据
 * @param msg 传递过来的数据
 * @returns 
 */
export function diyDecode(msg: any): { id: number, route: string, body: ProtoMod.IProtoReq } {
    const data = ProtoMod.unPack(msg.body);
    if(data === null) {
        return undefined;
    }
    //这里根据data解析出协议ID,内部做路由分发
    //前端服务器不想返回消息的话这里id=0
    if(routers[data.protoid] !== undefined) {
        return {id: 0, route: routers[data.protoid], body: data};    
    }
    return {id: 0, route: "connector.entryHandler.entry", body: data};
}

/**
 * 自定义加密数据
 * @param reqId 
 * @param route 
 * @param msg 
 * @returns 
 */
export function diyEncode(reqId: number, route: string, msg: ProtoMod.IProtoRevc): {id: number, body: Buffer} | Buffer {
    if(msg === undefined || msg === null || Object.keys(msg).length === 0) {
        return Buffer.from('');
    }
    if(msg['code'] !== undefined && msg['code'] > 0) {
        //这里有错误消息
        const err = new Err_revc();
        err.reason = Number(msg['code']);
        msg = err;
    }
    const data = ProtoMod.pack(msg);
    return data;
}